package com.nmgs.util;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.json.JSONObject;

import java.util.Map;

public class GetWebServiceData {
    public static String toWebService(String WebServiceID, Map<String, Object> paramsMap) {
        Object[] object = null;
        String port=PropertiesUtil.getValue("server.port");
        // 创建动态客户端
        String path = "http://8.142.95.188:"+port+"/WebService/MyWebService/GetWebServiceData?wsdl";
        String methodName = "GetWebServiceData";
        String params = new JSONObject(paramsMap).toString();
        int CXF_CLIENT_CONNECT_TIMEOUT = 2 * 60000;
        int CXF_CLIENT_RECEIVE_TIMEOUT = 2 * 60000;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(path);
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        conduit.setClient(policy);
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        //json的形式
        //JSONObject jsonMap = new JSONObject(params);
        Object[] aaa = new Object[]{WebServiceID, params};
        try {
            objects = client.invoke(methodName, aaa);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }
    public static String toWebService(String path, String methodName, Object[] params) {
        // 创建动态客户端
        Client client = getClient(path);
        Object[] objects;
        try {
            objects = client.invoke(methodName, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }
    public static Client getClient(String path) {
        // 创建动态客户端
        int CXF_CLIENT_CONNECT_TIMEOUT = 60 * 10000;
        int CXF_CLIENT_RECEIVE_TIMEOUT = 60 * 10000;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//        dcf.setJaxbContextProperties();
        Client client = dcf.createClient(path);
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        conduit.setClient(policy);
        return client;
    }
}
